import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { premissionRoutes, routes } from '@/router'
const initialState: UserStore.InitialState = {
  TOKEN: localStorage.getItem('token') || '',
  routes: routes,
}
const userStore = createSlice({
  name: 'user',
  // 初始化state
  initialState: initialState,
  //   修改方法 同步方法 支持直接修改
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(login.fulfilled, (state, { payload }) => {
        state.TOKEN = payload
        localStorage.setItem('token', payload)
      })
      .addCase(loginOut.fulfilled, (state, { payload }) => {
        if (payload) {
          state.TOKEN = ''
          localStorage.removeItem('token')
        }
      })
      .addCase(getPremissionRoutes.fulfilled, (state, { payload }) => {
        if (state.TOKEN !== '') {
          state.routes[0].children = payload
        }
      })
  },
})
export const login = createAsyncThunk('login', async () => {
  const res = await new Promise<string>((resolve) => {
    setTimeout(() => {
      resolve('存在Token')
    }, 1000)
  })
  return res
})
export const loginOut = createAsyncThunk('loginOut', async () => {
  const res = await new Promise<boolean>((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 300)
  })
  return res
})

export const getPremissionRoutes = createAsyncThunk('getPremissionRoutes', async () => {
  const res = await new Promise<RouteObject[]>((resolve) => {
    setTimeout(() => {
      resolve(premissionRoutes)
    }, 3000)
  })
  return res
})

const reducer = userStore.reducer
export default reducer
